package com.handong.handserialprogram.thread;

import android.content.Context;
import android.os.Process;
import android.support.annotation.RequiresPermission;
import android.util.Log;

import com.handong.handserialprogram.R;
import com.handong.handserialprogram.model.entities.FootRingNewEntity;
import com.handong.handserialprogram.model.status.FootRingStatus;
import com.handong.handserialprogram.model.status.RingResponse;
import com.handong.handserialprogram.module.serialport.SerialPortUtil;
import com.handong.handserialprogram.utils.CheckUtil;
import com.handong.handserialprogram.utils.EventBusUtil;
import com.handong.handserialprogram.utils.FootRingNewUtil;
import com.handong.handserialprogram.utils.JLog;
import com.handong.handserialprogram.utils.SPUtil;
import com.handong.handserialprogram.voice.VoiceImpl;

import java.io.IOException;
import java.io.InputStream;
import java.util.Vector;

import cn.pda.serialport.Tools;

import static com.handong.handserialprogram.thread.BaseRunnable.TAG;

/**
 * Created by zhongqiu on 2019/9/26.
 */

public class SendRunnable implements  Runnable {
    private static final byte TIME_SEND_WAIT = 3;
    //private Vector<FootRingNewEntity> mRingList;
    private SerialPortUtil mSerialPortUtil;
    private byte  mUploadCount;
    private ReadNewRunnable mReadRunnable;
    boolean isRunning=true;
    protected boolean mIsWorking = true;
    public boolean isPause=false;
    private Context mAppContext;
//    private boolean isFirst=true;

    public int DelayTime=30;//发送命令过后等待的时间 ms

    private int RefreshCount=1;//刷新界面时间，1代表500ms
    private int currentPlayWarningCount=0;//当前播放报警次数
    private int PlayWarningCount=3;//报警次数
    private int currentCount=0;

    private int SleepTime=1500;//整个大循环的时间 ms
    private int WakeUpWaitTime=350;//唤醒的时间 ms
    private VoiceImpl mVoiceImpl;
    private boolean isPlaying=false;
    public boolean isLoginOut=false;
    private boolean loginState=false;
    private int loginCount=0;


//    private CallBackUtil.OnSendDataListener onSendDataListener;

//    /**
//     * 注册回调接口的方法，供外部调用
//     * @param onSendDataListener
//     */
//    public void setOnSendDataListener(CallBackUtil.OnSendDataListener onSendDataListener) {
//        this.onSendDataListener = onSendDataListener;
//    }

    //public void setmRingList(Vector<FootRingNewEntity> mRingList) {
     //   this.mRingList = mRingList;
    //}

    public SendRunnable(SerialPortUtil serialPortUtil,Context context, ReadNewRunnable readNewRunnable) {
        //this.mRingList = ringList;
        this.mSerialPortUtil = serialPortUtil;
        this.mReadRunnable=readNewRunnable;
        this.DelayTime=30;
        this.mAppContext=context;
    }


    private boolean mIsUploadLocation = false;
    private static final byte TIME_WAIT = 9;


    @Override
    public void run() throws RuntimeException {
        Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
        while (mIsWorking) {
            long startTime=System.currentTimeMillis();

            try {

                try {
                    if (mSerialPortUtil.mRingList == null) {
                        continue;
                    }
                    search4ActiveFootRing();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            } catch (RuntimeException e) {
                e.printStackTrace();
                JLog.d(TAG, e.toString());
                break;
            }
            if (!mIsWorking) {
                break;
            }
            long passTime=System.currentTimeMillis()-startTime;
            if (passTime<SleepTime)
            {
                try {
                    Thread.sleep(SleepTime-passTime);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            if(currentCount>=RefreshCount) {
                currentCount=0;
                mReadRunnable.IsFresh=true;
            }
            currentCount++;


            if (isPlaying) {
                if (currentPlayWarningCount >= PlayWarningCount) {
                    currentPlayWarningCount = 0;
                    isPlaying=false;
                } else {
                    currentPlayWarningCount++;
                }
            }
            else{
                isPlaying=playWarningRing();
                currentPlayWarningCount = 0;
            }

        }
        releaseRes();

    }


    /**
     * 播放警报
     */
    private boolean playWarningRing() {

        if (mVoiceImpl == null) {
            mVoiceImpl = VoiceImpl.getInstance(mAppContext);
        }
        return mVoiceImpl.playVoice();
    }






    /**
     * 查找并激活脚环。
     */
    private void search4ActiveFootRing() throws IOException, InterruptedException {
            //发送唤醒命令
//            FootRingNewEntity wakeupEntity=new FootRingNewEntity();
//            wakeupEntity.setTask((byte)0x10);
//            mSerialPortUtil.sendFootRing(wakeupEntity);
//            Thread.sleep(WakeUpWaitTime);
            byte i=1;
            for (FootRingNewEntity entity :
                    mSerialPortUtil.mRingList) {
                    entity.setUwbCycle(i);
                    i++;
                if (!loginState&&isLoginOut)
                {
                    //原本是正常,开始注销
                    if (entity.isNormalWork()) {
                        entity.setActionOrder(RingResponse.LOGOUT_ORDER);
                        entity.setStopMissionReceive(false);
                        entity.setStopMissionNoDataCount(0);
                        entity.setLoginOutAlarm(true);
                    }
                }else if(loginState&&!isLoginOut){
                    //原本是注销，恢复正常
                    entity.setLoginOutAlarm(false);
                }
                    mSerialPortUtil.sendFootRing(entity);
                    entity.setReceiveData(false);
                    mReadRunnable.ringId = entity.getRingID();


                    long startTime = System.currentTimeMillis();
                    while (!mReadRunnable.DoWork(entity.getRingID(), false)) {
                        Thread.sleep(1);
                        if (System.currentTimeMillis() - startTime >= DelayTime) {
                            mReadRunnable.DoWork(entity.getRingID(), true);
                            //isReceive=false;
                            break;
                        }
                    }



            }
        if (!loginState&&isLoginOut)
        {
            //原本是正常,开始注销
            loginState=true;
            loginCount=0;
        }else if(loginState&&!isLoginOut){
            //原本是注销，恢复正常
            loginState=false;
            loginCount=0;
        }
        if (loginState)
        {
            boolean isLoginTimeOut=false;
            boolean isLoginOutFail=false;

            for (FootRingNewEntity entity :
                    mSerialPortUtil.mRingList) {

                if (loginCount>=10)
                {
                    isLoginTimeOut=true;
                    entity.resetActionCount();
                    entity.setActionOrder(RingResponse.NO_ACTION_ORDER);//重置为已处理
                }
                if (entity.isNormalWork())
                {
                    isLoginOutFail=true;
                }
            }
            if(loginState&&isLoginOutFail&&loginCount>=10){
                isLoginOut=false;
                loginState=false;
                sendDealOrder(mSerialPortUtil.mRingList.get(0), RingResponse.LOGOUT_ORDER, false);
            }
            else if(loginState&&!isLoginOutFail)
            {
                isLoginOut=false;
                loginState=false;
                sendDealOrder(mSerialPortUtil.mRingList.get(0), RingResponse.LOGOUT_ORDER, true);
            }
            loginCount=loginCount+1;
        }



//            if (isFirst)
//            {
//                isFirst=false;
//                this.DelayTime=30;
//            }
        mReadRunnable.refreshAllFootRing();//刷新界面
        if(!isPause) {
            mSerialPortUtil.refreshRingList();//上传到服务器
        }

        }

    /**
     * 发送处理脚环结果
     */
    private void sendDealOrder(FootRingNewEntity entity, byte order, boolean isSuccess) {
        if (entity == null) {
            return;
        }
        entity.resetActionCount();
        entity.setActionOrder(RingResponse.NO_ACTION_ORDER);//重置为已处理
        EventBusUtil.post(new RingResponse(entity.getRingID(), order, isSuccess));
    }

    /**
     * 关闭线程。
     */
    public void destroy() {
        mIsWorking = false;
    }


    public void releaseRes() {
        mSerialPortUtil = null;
        mUploadCount = 0;
    }
}
